<?php

namespace app\common\services;

use app\admin\model\yalimedia\question\Log;
use app\common\model\YalimediaQuestionLog as logModel;
use app\common\model\YalimediaQuestionLogDetail as detailModel;
use think\Db;

use addons\exam\model\QuestionModel;

use think\facade\Cache;

class QuestionLogService
{
    
    // 答题记录
    public static function info($id){
        
        $info = logModel::where('id',$id)->find();
        return $info;
    }
    
    /**
     * 答题记录
     */
    public static function add($data){
        
        $model = new logModel;
        $model->allowField(true)->save($data);
    }


    /**
     * 添加答题记录
     *
     * @return void
     */
    public static function addLog($data,$user_questions,$end){

        $logModel = new logModel;
        $log      = $logModel->where(['status'=>1,'user_id' => $data['user_id'], 'course_id' => $data['course_id']])->find();
        $time     = time();
        if(empty($log)){
            
            $data['createtime'] = $time;
            $data['updatetime'] = $time;
            $log_id = $logModel->allowField(true)->insertGetId($data);
        }else{

            $log_id = $log['id'];
            $logModel->allowField(true)->save($data,['id' => $log_id]);
        }
        
        // 试题ID
        $question_ids = explode(',',$data['question_ids']);
 

        foreach ($question_ids as $key=>$value) {

            $save['user_id']     = $data['user_id'];
            $save['log_id']      = $log_id;
            $save['course_id']   = $data['course_id'];
            $save['content']     = $user_questions ? json_encode($user_questions[$value],JSON_UNESCAPED_UNICODE):json_encode([]);
            $save['question_id'] = $value;

            $detail = detailModel::where(['user_id' => $data['user_id'],'log_id' => $log_id,'question_id' => $value])->find();
            try{

                if(empty($detail)){
                    detailModel::create($save);
                }else{
                    $detail->save($save);
                }
            }catch(\Exception $e){
            }
        }
        $data = detailModel::field('content')->where(['user_id' => $data['user_id'],'log_id' => $log_id])->select();

        $rids = [];
        $eids = [];
        $qids = [];
        foreach ($data as $v){
            $jsonArr = json_decode($v['content'],true);
            if(!$jsonArr) continue;
            $qids[] = $jsonArr['id'];
            if(isset($jsonArr['is_right']) && $jsonArr['is_right']){
                $rids[] = $jsonArr['id'];
            }else{
                $eids[] = $jsonArr['id'];
            }
        }
        $allids = explode(',',Log::where('id',$log_id)->value('all_question_ids'));
        $emtyids = $allids;
        foreach ($emtyids as $k=>$v){
            if(in_array($v,$rids) || in_array($v,$eids)){
                unset($emtyids[$k]);
            }
        }
        $upda = ['question_ids'=>implode(",",$qids),'right_ids'=>implode(",",$rids),'empty_ids'=>implode(",",$emtyids),'error_ids'=>implode(",",$eids),'right_count'=>count($rids),'error_count'=>count($eids),'empty_count'=>count($emtyids)];
        if($end){
            $upda['last'] = $end['id'];
        }
        Log::where('id',$log_id)->update($upda);
    }


    /**
     * 提交答案
     *
     * @param [int] $user_id
     * @param [int] $course_id
     * @return void
     */
    public static function submit($user_id,$course_id,$type){

        $log = logModel::where(['user_id'=>$user_id,'course_id'=>$course_id,'status'=>1])->find();
        if(empty($log)){
            return ['code'=>0,'msg'=>'记录不存在'];
        }

        if($log['status'] == 2){
            return ['code'=>1,'msg'=>'记录已提交','log_id'=>$log['id']];
        }

        try{

            
            //  记录更新为已完成
            if($type == 0 || !$type){
                Db::startTrans();
                $log->save(['status'=>2]);
                //  题目详情更新为已完成
                detailModel::where([ 'log_id'=>$log['id'] ])->update(['status'=>2]);
                Db::commit();
            }

            return ['code'=>1,'msg'=>'success','log_id'=>$log['id']];
        }catch(\Exception $e) {
            Db::rollback();
            return ['code'=>0,'msg'=>'提交失败:'.$e->getMessage()];
        }
    }



    /**
     * 获取答题记录
     *
     * @return void
     */
    public static function getLog($user_id,$course_id,$page_info){
        
        $list = logModel::where(['user_id'=>$user_id,'course_id'=>$course_id,'status'=>2])
            ->order('id DESC')
            ->paginate($page_info['num'])
            ->toArray();
        
        $new_list = [];
        foreach ($list['data'] as $key => $value) {
 
            foreach ($value['all_question_ids'] as $k => $v) {
     
                if(!empty($value['right_ids'])){
                    if(isset(array_flip($value['right_ids'])[$v])){
                        $status = 1;
                    };
                }
                
                if(!empty($value['error_ids'])){
                    if(isset(array_flip($value['error_ids'])[$v])){
                        $status = 2;
                    };
                }

                if(!empty($value['empty_ids'])){
                    if(isset(array_flip($value['empty_ids'])[$v])){
                        $status = 3;
                    };
                }
                $new_list[$key]['list'][$k]['id']     = $v;
                $new_list[$key]['list'][$k]['status'] = $status;
            }
            $new_list[$key]['id']     = $value['id'];
            $new_list[$key]['time']   = date('Y-m-d H:i:s',$value['createtime']);
            $new_list[$key]['total']  = count($value['all_question_ids']) ?? 0;
            $new_list[$key]['right_count']  = current($list['data'])['right_count'] ?? 0;
        }

        return $new_list;
    }


    /**
     * 试题记录详情
     *
     * @return void
     */
    public static function detail($ids,$id,$user_id,$log_id){
        
        // 获取试题列表
        $list = QuestionModel::getQuestionDetail($ids,$id,$user_id,$log_id);
        return $list;
    }

}